package com.udata.server.dao.impl;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.google.gson.Gson;
import com.udata.server.dao.TiebaExpDao;
import com.udata.server.util.PMF;
import com.udata.shared.exception.OperationException;
import com.udata.server.model.TiebaExp;

public class TiebaExpDaoImpl extends TiebaExpDao {

	@Override
	public TiebaExp saveTiebaExp(TiebaExp te) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(te);
		} finally {
			pm.close();
		}
		return te;
	}

	@Override
	public Boolean saveData(String category, Integer pageNum)
			throws OperationException {
		try {
//			String categoryDB = URLEncoder.encode(category, "gbk");
			List<String> names = null;
			List<Integer> exps = null;
			String dateStr = this.getToday();
			TiebaExp te = null;
			Pattern namePattern = Pattern.compile("username=\"([\\w%]*)\">");
			Pattern expPattern = Pattern
					.compile("<td class=\"drl_item_exp\"><span>([\\d]*)</span></td> ");
			String url = null;
			String content = null;
			Matcher m = null;
			for (int i = 1; i <= pageNum; i++) {
				names = new ArrayList<String>();
				exps = new ArrayList<Integer>();
				System.out.println(i);

				url = "http://tieba.baidu.com/f/like/furank?kw=" + category
						+ "&pn=" + i;
				content = this.getFile(url);
				System.out.println(content);
				// String content="username=test";

				m = namePattern.matcher(content);

				while (m.find()) {
					names.add(m.group(1));
				}
				m = expPattern.matcher(content);
				while (m.find()) {
					exps.add(Integer.valueOf(m.group(1)));
				}

				System.out.println(names.size());
				System.out.println(names);
				for (int j = 0; j < names.size(); j++) {
					te = new TiebaExp();
					te.setName(names.get(j));
					te.setCategory(category);
					te.setExp(exps.get(j));
					te.setCreateDate(dateStr);
					this.saveTiebaExp(te);
				}
			}

			return true;
		} catch (Exception e) {
			throw new OperationException(e.getMessage());
		}
	}

	public String getFile(String urlStr) {
		StringBuffer document = new StringBuffer();
		try {
			URL url = new URL(urlStr);
			URLConnection conn = url.openConnection();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					conn.getInputStream(), "gbk"));
			String line = null;
			while ((line = reader.readLine()) != null)
				document.append(line + " ");
			reader.close();
		} catch (Exception e) {
		}

		return document.toString();
	}

	@Override
	public Boolean saveData(String category) throws OperationException {
		try {
			category = URLEncoder.encode(category, "gbk");


			String url = "http://tieba.baidu.com/f/like/furank?kw=" + category
					+ "&pn=" + 1;
			String content = this.getFile(url);
			System.out.println(content);
			// String content="username=test";
			Pattern memberNumPattern = Pattern
					.compile("<span class=\"drl_info_txt_gray\">([\\d]+)</span>");

			Matcher m = memberNumPattern.matcher(content);
			Integer memberNum = 0;
			if (m.find()) {
				memberNum = Integer.valueOf(m.group(1));
				System.out.println("member number:" + memberNum);
			}
			Integer pageNum = (int) Math.ceil(memberNum / 20.0);
			pageNum=1;
			System.out.println("Page num:" + pageNum);

			this.saveData(category, pageNum);

			return true;

		} catch (Exception e) {
			throw new OperationException(e.getMessage());
		}

	}

	@Override
	public String getJsonData(String category) throws OperationException {
		try {
			String categoryDB = URLEncoder.encode(category, "gbk");
			PersistenceManager pm = PMF.get().getPersistenceManager();
			Query query = pm.newQuery(TiebaExp.class);
			query.setFilter("category == '" + categoryDB + "' && createDate=='"
					+ this.getToday()+"'");
			List<TiebaExp> results = (List<TiebaExp>) query.execute();
			if (results.size() == 0) {
				this.saveData(category);
			}
			results = (List<TiebaExp>) query.execute();
			Gson gson = new Gson();

			return gson.toJson(results);
		} catch (Exception e) {
			throw new OperationException(e.getMessage());
		}
	}

	private String getToday() {
		DateFormat df = new SimpleDateFormat("yyyyMMdd");
		Date date = new Date(System.currentTimeMillis());
		String dateStr = df.format(date);
		return dateStr;
	}

}
